#!/usr/bin/env python3
# encoding=utf-8

import os
import with_win32 as wwin32
from word_with_image import replace_word_png
from commom_api import get_product_name_prefix, get_doc_fill_base_info

import logging
logger = logging.getLogger(__name__)

def fill_win32_table_header_info(wtb, sheet, xlsinfo):
    maxrow = xlsinfo['flexiblepos'][2]

    # 产品名称
    cell = wtb.Cell(1, 1).Range
    cell.Font.Bold = True
    pname = get_product_name_prefix(os.path.basename(xlsinfo['excel']))
    suffix = get_product_name_prefix(cell.Text, order=1).replace('\r', '').replace('\n', '')
    cell.Text = f'{pname}{suffix}'
    
    # 起始日期
    cell = wtb.Cell(2, 2).Range
    cell.Text = xlsinfo['daterange'][0].strftime("%Y/%m/%d")
    
    # 计算日期
    cell = wtb.Cell(2, 4).Range
    cell.Text = xlsinfo['daterange'][2].replace('-', '/')
    
    # 涨幅
    cell = wtb.Cell(2, 6).Range
    val = sheet.Cells(maxrow-1, 3).Value
    val1 = sheet.Cells(maxrow, 3).Value
    cell.Text = "%.02f%%" % ((val1 - val)/val*100)

def set_wn32_cell_format(cell, mval, num=1):
    if num < 1:
        return
    # color
    if 'color' in mval and len(mval) >= 3*num:
        st = (num - 1) * 3
        rgb= mval['color'][st:st+3]
    else:
        rgb = [0, 0, 0]
    cell.Font.Color = (rgb[2] << 16) | (rgb[1] << 8) | rgb[0]  # 设置颜色

    # bold
    if 'bold' in mval and len(mval) >= num:
        bold = True if mval['bold'][num-1] else False
    else:
        bold = False
    cell.Font.Bold = bold  # 设置粗体

def fill_win32_table_info(wtb, sheet, xlsinfo):
    docname, mode = get_doc_fill_base_info(xlsinfo['code'], xlsinfo['daterange'][0])
    if mode == None:
        return
    
    for key, mval in mode.items():
        if 'wpos' not in mval:
            continue
        if wtb.Rows.Count < mval['wpos'][0] or wtb.Columns.Count < mval['wpos'][1]:
            logger.error(f'max word table [{wtb.Rows.Count},{wtb.Columns.Count}], please check you config.json')
            continue
        xpos = mval['xpos']
        wpos = mval['wpos']
        cell = wtb.Cell(wpos[0], wpos[1]-1).Range
        cell.Text = key
        set_wn32_cell_format(cell, mval, 1)

        
        cell = wtb.Cell(wpos[0], wpos[1]).Range
        if isinstance(xpos, list):
            val = sheet.Cells(xpos[0], xpos[1]).Value
        elif isinstance(xpos, str):
            if xpos not in xlsinfo:
                continue
            xpos = [xlsinfo['flexiblepos'][2], xlsinfo[xpos][0]]
            val = sheet.Cells(xpos[0], xpos[1]).Value
        else:
            continue
        if 'number' in mval:
            if mval['number'] == '%':
                cell.Text = "%.02f%%" % (val*100)
            else:
                cell.Text = f"{mval['number']}" % (val)
        else:
            cell.Text = f"{val}"
        set_wn32_cell_format(cell, mval, 2)

def fill_win32cell_by_excelinfo(sheet, wordpath, xlsinfo):
    try:
        with wwin32.Win32AppManager(wordpath) as (word, doc):
            tb = doc.Tables(1)
            fill_win32_table_header_info(tb, sheet, xlsinfo)
            fill_win32_table_info(tb, sheet, xlsinfo)
            # tb.Range.ParagraphFormat.Alignment = win32.constants.wdAlignParagraphCenter
            doc.SaveAs(wordpath)   
    except Exception as e:
        logging.error(f"myword {wordpath} cell error[{e}]")
        wwin32.kill_excel_process()  # 兜底清理
        
    logging.info(f'fill word data pass {wordpath}')
    pngpath = xlsinfo['excel'].replace('.xlsx', '.png')
    replace_word_png(wordpath, pngpath)
 